<template>
  <view class="friends-page">
    <!-- 顶部导航栏 -->
    <view class="header-bar">
      <view class="header-left">
        <button class="back-btn" @click="goBack">← 返回</button>
      </view>
      <view class="header-title">好友管理</view>
      <view class="header-right">
        <button class="add-btn" @click="goToAddFriend">+ 添加</button>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section">
      <view class="search-container">
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索用户昵称..." 
          class="search-input"
          @input="onSearch"
        />
        <button class="search-btn" @click="onSearch">搜索</button>
      </view>
    </view>

    <!-- 好友列表 -->
    <view class="friends-list">
      <view v-if="loading" class="loading-spinner">
        <span class="spinner"></span>
        <text>加载中...</text>
      </view>
      
      <view v-else-if="friends.length" class="friends-container">
        <view 
          v-for="friend in filteredFriends" 
          :key="friend.id" 
          class="friend-item"
          @click="startChat(friend)"
        >
          <image :src="getAvatarUrl(friend.avatarUrl || friend.friendAvatarUrl)" class="friend-avatar" @error="handleFriendAvatarError" />
          <view class="friend-info">
            <text class="friend-name">{{ friend.nickname || friend.friendNickname }}</text>
            <text class="friend-status" :class="{ online: friend.isOnline }">
              {{ friend.isOnline ? '在线' : '离线' }}
            </text>
          </view>
          <view class="friend-actions">
            <button class="chat-btn" @click.stop="startChat(friend)">聊天</button>
            <button class="delete-btn" @click.stop="deleteFriend(friend)">删除</button>
          </view>
        </view>
      </view>
      
      <view v-else class="empty-state">
        <view class="empty-icon">👥</view>
        <text class="empty-title">暂无好友</text>
        <text class="empty-desc">点击右上角添加好友</text>
      </view>
    </view>

  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/store/user'
import { getAvatarUrl } from '@/utils/imageUtils.js'

const userStore = useUserStore()

// 数据
const loading = ref(false)
const friends = ref([])
const searchKeyword = ref('')

// 计算属性
const filteredFriends = computed(() => {
  if (!searchKeyword.value) return friends.value
  return friends.value.filter(friend => {
    const name = friend.nickname || friend.friendNickname || ''
    return name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  })
})

// 初始化
onMounted(() => {
  loadFriends()
})

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 跳转到添加好友页面
const goToAddFriend = () => {
  uni.navigateTo({
    url: '/pages/social/friends-add/index'
  })
}

// 加载好友列表
const loadFriends = async () => {
  loading.value = true
  try {
    const token = uni.getStorageSync('accessToken')
    if (!token) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const response = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/friends`,
      method: 'GET',
      header: {
        'Access-Token': `Bearer ${token}`
      }
    })

    if (response.data && response.data.code === 200) {
      friends.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载好友列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}


// 开始聊天
const startChat = (friend) => {
  // 修复：应该使用 friendId 而不是 id
  // id 是好友关系记录的ID，friendId 才是好友的用户ID
  const friendId = friend.friendId || friend.id
  const friendName = friend.nickname || friend.friendNickname || '未知用户'
  
  console.log('开始聊天调试信息:')
  console.log('好友对象:', friend)
  console.log('好友ID (friendId):', friend.friendId, '类型:', typeof friend.friendId)
  console.log('记录ID (id):', friend.id, '类型:', typeof friend.id)
  console.log('选择的聊天用户ID:', friendId, '类型:', typeof friendId)
  console.log('好友名称:', friendName)
  
  uni.navigateTo({
    url: `/pages/social/chat-detail?userId=${friendId}&name=${encodeURIComponent(friendName)}`
  })
}

// 删除好友
const deleteFriend = (friend) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除好友 ${friend.nickname} 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const token = uni.getStorageSync('accessToken')
          const response = await uni.request({
            url: `${NETWORK_CONFIG.API_BASE_URL}/friends/${friend.friendId}`,
            method: 'DELETE',
            header: {
              'Access-Token': `Bearer ${token}`
            }
          })

          if (response.data && response.data.code === 200) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadFriends() // 重新加载好友列表
          } else {
            uni.showToast({
              title: response.data?.message || '删除失败',
              icon: 'none'
            })
          }
        } catch (error) {
          console.error('删除好友失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 搜索好友
const onSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

// 错误处理
const handleFriendAvatarError = () => {
  console.log('好友头像加载失败')
}
</script>

<style scoped>
.friends-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.header-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #4A90E2;
  color: white;
}

.header-left, .header-right {
  flex: 1;
}

.header-title {
  flex: 2;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
}

.back-btn, .add-btn {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  padding: 8px 12px;
  border-radius: 4px;
}

.back-btn:hover, .add-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.search-section {
  padding: 16px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
}

.search-container {
  display: flex;
  gap: 8px;
}

.search-input {
  flex: 1;
  height: 40px;
  padding: 0 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 14px;
}

.search-btn {
  padding: 0 16px;
  height: 40px;
  background: #4A90E2;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
}

.friends-list {
  flex: 1;
  padding: 16px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #4A90E2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.friends-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.friend-avatar {
  width: 50px;
  height: 50px;
  border-radius: 25px;
  margin-right: 12px;
  object-fit: cover;
}

.friend-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.friend-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.friend-status {
  font-size: 12px;
  color: #999;
}

.friend-status.online {
  color: #4CAF50;
}

.friend-actions {
  display: flex;
  gap: 8px;
}

.chat-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 16px;
  font-size: 12px;
}

.chat-btn {
  background: #4A90E2;
  color: white;
}

.delete-btn {
  background: #F44336;
  color: white;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #999;
}

</style>